package com.zzw.gatewayfilter.tokenfilter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.HasRouteId;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpStatus;

/**
 * @author Administrator
 */
public class TokenFilterGatewayFilterFactory extends AbstractGatewayFilterFactory<TokenFilterGatewayFilterFactory.Config> {

    private final TokenFilter tokenFilter;

    public TokenFilterGatewayFilterFactory(TokenFilter tokenFilter) {
        super(Config.class);
        this.tokenFilter = tokenFilter;
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> tokenFilter.isAllowed(config.getRequestHeaderKey()).flatMap(response -> {
            if (response.isAllowed()) {
                return chain.filter(exchange);
            } else {
                ServerWebExchangeUtils.setResponseStatus(exchange, config.getStatusCode());
                return exchange.getResponse().setComplete();
            }
        });
    }

    public static class Config implements HasRouteId {
        private String routeId;
        private String requestHeaderKey;
        private HttpStatus statusCode = HttpStatus.UNAUTHORIZED;

        public HttpStatus getStatusCode() {
            return statusCode;
        }

        public void setStatusCode(HttpStatus statusCode) {
            this.statusCode = statusCode;
        }

        public String getRequestHeaderKey() {
            return requestHeaderKey;
        }

        public void setRequestHeaderKey(String requestHeaderKey) {
            this.requestHeaderKey = requestHeaderKey;
        }

        @Override
        public String getRouteId() {
            return routeId;
        }

        @Override
        public void setRouteId(String routeId) {
            this.routeId = routeId;
        }
    }
}
